package controllers.systemadmin

import javax.inject.Inject

import controllers.BaseController
import models.{Role, RoleQuery}
import repos.RoleRepository

import scala.concurrent.ExecutionContext.Implicits.global
class RoleController @Inject()(roleRepository: RoleRepository) extends BaseController {

  import models.JsonFormatters._
  import roleRepository.dbConfig.driver.api._

  def list = authJsonAction[RoleQuery](Array("admin")) {
    (param, request) =>
      roleRepository.filter({ r =>
         r.id === param.id &&
          param.roleCode.map(r.roleCode === _).getOrElse(LiteralColumn(true)) &&
          param.roleName.map(r.roleName like _).getOrElse(LiteralColumn(true)) &&
          param.roleDescrition.map(r.roleDescrition like _).getOrElse(LiteralColumn(Option(true)))
      }, param.page.getOrElse(1), param.pageSize match {
        case Some(_) => param.pageSize
        case None => Some(25)
      }).map {
        case (total, roles) =>
          Map("success" -> true,
            "resultCode" -> 0,
            "message" -> "list complete",
            "total" -> total,
            "data" -> roles)
      }
  }

  def single = TODO

  def add = authJsonAction[Role](Array("admin")) {
    (param, request) =>
      roleRepository.save(param)
        .map { role =>
          Map("success" -> true,
            "resultCode" -> 0,
            "message" -> "add complete",
            "data" -> role.id)
        }
  }

  def remove = authJsonAction[RoleQuery](Array("admin")) {
    (param, request) =>
      roleRepository.remove(param.id.get)
        .map { role =>
          Map("success" -> true,
            "resultCode" -> 0,
            "message" -> "remove complete")
        }
  }

  def modify = authJsonAction[Role](Array("admin")) {
    (param, request) =>
      roleRepository.update(param)
        .map { role =>
          Map("success" -> true,
            "resultCode" -> 0,
            "message" -> "modify complete")
        }
  }
}
